import { childrenProps, BasicForm, FormKeys } from '@/components/ProForm/interface/index';
import { PublicInterface } from '@/interface/public';

import { defaultStyle } from '@/basic/style';
import { PositionInterface } from '@/api/interface/dept/position';

export function usePositionForm(proTableBox: PublicInterface.ProTableValue) {
  let positionForm = reactive<BasicForm<PositionInterface.ReqSave>>({
    form: {
      id: null,
      name: '',
      pid: null,
      deptId: null,
      sort: null,
      remark: ''
    },
    title: '',
    visible: false,
    options: [
      {
        label: 'id',
        prop: 'id',
        hide: true,
        type: 'input',
        defaultValue: ''
      },
      {
        type: 'cascader',
        label: '关联部门',
        hide: false,
        defaultValue: [],
        prop: 'deptId',
        attrs: {
          options: []
        },
        rules: [{ required: true, message: '关联部门', trigger: 'blur' }]
      },
      {
        type: 'input',
        label: '岗位名称',
        hide: false,
        prop: 'name',
        defaultValue: '',
        rules: [{ required: true, message: '部门名称', trigger: 'blur' }]
      },
      {
        type: 'select',
        label: '所属上级',
        hide: false,
        defaultValue: 0,
        prop: 'pid',
        children: [],
        attrs: {
          clearable: true
        }
      },
      {
        type: 'input',
        label: '排序',
        hide: false,
        prop: 'sort',
        defaultValue: ''
      },
      {
        type: 'input',
        label: 'remark',
        defaultValue: '',
        hide: false,
        prop: 'remark',
        attrs: {
          style: defaultStyle
        }
      }
    ]
  });

  const saveAddPositionForm = async (form: PositionInterface.ReqSave) => {
    const params: any = { ...form };
    params.deptId = setDeptId(params);
    params.pid = !params.pid ? 0 : params.pid;

    await positionSave(params);
    positionForm.visible = false;
    elMessage();
    proTableBox.value?.getTableList();
  };

  const setDeptId = params => {
    let deptId = null;
    if (typeof params.deptId === 'number') {
      deptId = params.deptId;
    } else {
      deptId = params.deptId[params.deptId.length - 1];
    }
    return deptId;
  };

  /**
   * 获取表单中的选择数据
   */
  const getAddPositionFormChildren = async () => {
    const res = await promiseAllApi([positionListFindFlattenTree(), deptListByFlattenTree({ status: BasicKey.ENABLE })]);

    const children: Map<FormKeys<PositionInterface.ReqSave>, childrenProps[]> = new Map();
    children.set('pid', arrTransitionSelectData<any>(res[0], 'name', 'id'));
    children.set('deptId', arrTransitionTreeData<any>(res[1], 'name', 'id'));
    formSetChildren(positionForm, children);
  };

  return { positionForm, saveAddPositionForm, getAddPositionFormChildren };
}
